// recipeList.js
const app = getApp()

Page({
  data: {
    categoryId: null,
    categoryName: '',
    recipes: [],
    loading: true,
    error: false
  },

  onLoad: function(options) {
    const { categoryId, categoryName } = options;
    
    // 检查必要参数
    if (!categoryId) {
      this.setData({ 
        loading: false,
        error: true 
      });
      wx.showToast({
        title: '分类ID无效，无法加载',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ categoryId, categoryName });
    
    // 直接加载本地数据
    this.loadLocalRecipes(categoryId);
  },

  onShow: function() {
    // 页面显示时重新加载数据
    if (this.data.categoryId) {
      this.loadLocalRecipes(this.data.categoryId);
    }
  },

  loadLocalRecipes(categoryId) {
    if (!categoryId) {
      wx.showToast({
        title: '分类ID无效',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true, error: false });
    
    try {
      // 确保app.globalData.recipes存在
      if (!Array.isArray(app.globalData.recipes)) {
        app.globalData.recipes = [];
      }

      // 转换categoryId为字符串进行比较
      const targetCategoryId = categoryId.toString();
      
      // 预处理recipes数据，确保categoryId为字符串
      const recipes = app.globalData.recipes.map(recipe => ({
        ...recipe,
        categoryId: (recipe.categoryId || '').toString()
      }));
      
      const filteredRecipes = recipes.filter(recipe => recipe.categoryId === targetCategoryId);
      
      console.log('加载本地配方数据:', filteredRecipes);
      this.setData({
        recipes: filteredRecipes,
        loading: false
      });
      
      // 如果没有找到配方，显示空状态
      if (filteredRecipes.length === 0) {
        console.log('该分类下没有配方');
      }
    } catch (error) {
      console.error('加载配方失败:', error);
      this.setData({
        loading: false,
        error: true
      });
    }
  },

  retryLoad() {
    if (this.data.categoryId) {
      this.loadLocalRecipes(this.data.categoryId);
    }
  },

  goToRecipeDetail(e) {
    const { id } = e.currentTarget.dataset;
    if (!id) {
      wx.showToast({
        title: '配方ID无效',
        icon: 'none'
      });
      return;
    }
    
    // 使用navigateTo替代redirectTo
    wx.navigateTo({
      url: `/pages/recipeDetail/recipeDetail?id=${id}`
    });
  },

  createNewRecipe() {
    // 使用redirectTo替代navigateTo，避免页面堆栈问题
    wx.redirectTo({
      url: `/pages/recipeEdit/recipeEdit?categoryId=${this.data.categoryId}`
    });
  },

  onPullDownRefresh() {
    // 刷新数据
    if (this.data.categoryId) {
      this.loadLocalRecipes(this.data.categoryId);
    }
    wx.stopPullDownRefresh();
  }
}); 